package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyy.common.PageResult;
import com.xyy.dto.PushCommentDTO;
import com.xyy.dto.PushLikeDTO;

import com.xyy.entity.Push;
import com.xyy.entity.PushLike;
import com.xyy.entity.PushComment;
import com.xyy.mapper.PushMapper;
import com.xyy.mapper.PushLikeMapper;
import com.xyy.mapper.PushCommentMapper;
import com.xyy.service.UserPushService;
import com.xyy.vo.PushCommentVO;
import com.xyy.entity.User;
import com.xyy.service.UserService;
import com.xyy.vo.UserPushVO;
import com.xyy.dto.PushQueryDTO;
import com.xyy.vo.PushVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 用户端推文服务实现类
 */
@Slf4j
@Service
public class UserPushServiceImpl implements UserPushService {

    @Autowired
    private PushMapper pushMapper;

    @Autowired
    private PushLikeMapper pushLikeMapper;

    @Autowired
    private PushCommentMapper pushCommentMapper;

    @Autowired
    private UserService userService;


    @Override
    public PageResult<UserPushVO> getPushList(Integer current, Integer size, Long userId) {
        // 使用与管理端一致的自定义分页查询，避免逻辑删除字段导致的过滤问题
        Page<PushVO> page = new Page<>(current, size);
        PushQueryDTO queryDTO = new PushQueryDTO();
        // 不限制发布者，不限定状态，按时间倒序由 XML 控制
        IPage<PushVO> pushPage = pushMapper.selectPushPage(page, queryDTO);

        // 转换为用户端 VO
        List<UserPushVO> userPushVOList = pushPage.getRecords().stream()
            .map(record -> {
                UserPushVO vo = new UserPushVO();
                BeanUtils.copyProperties(record, vo);
                return vo;
            })
            .collect(Collectors.toList());

        // 设置是否已点赞
        if (userId != null) {
            for (UserPushVO vo : userPushVOList) {
                QueryWrapper<PushLike> likeQuery = new QueryWrapper<>();
                likeQuery.eq("push_id", vo.getId()).eq("user_id", userId);
                PushLike userLike = pushLikeMapper.selectOne(likeQuery);
                vo.setIsLiked(userLike != null);
            }
        } else {
            userPushVOList.forEach(item -> item.setIsLiked(false));
        }

        return PageResult.of(userPushVOList, pushPage.getTotal(), (long) current, (long) size);
    }

    @Override
    public UserPushVO getPushById(Long pushId, Long userId) {
        // 查询推文详情（仅未删除）
        QueryWrapper<Push> pushQuery = new QueryWrapper<>();
        pushQuery.eq("id", pushId).isNull("deleted_at");
        Push push = pushMapper.selectOne(pushQuery);
        if (push == null) {
            throw new RuntimeException("推文不存在");
        }

        // 转换为VO对象
        UserPushVO userPushVO = convertToUserPushVO(push);

        // 检查当前用户是否已点赞
        if (userId != null) {
            QueryWrapper<PushLike> likeQuery = new QueryWrapper<>();
            likeQuery.eq("push_id", pushId).eq("user_id", userId);
            PushLike userLike = pushLikeMapper.selectOne(likeQuery);
            userPushVO.setIsLiked(userLike != null);
        } else {
            userPushVO.setIsLiked(false);
        }

        // 增加浏览次数（原子自增）
        UpdateWrapper<Push> viewInc = new UpdateWrapper<>();
        viewInc.eq("id", pushId).isNull("deleted_at").setSql("view_count = view_count + 1");
        pushMapper.update(null, viewInc);

        return userPushVO;
    }

    @Override
    @Transactional
    public void likePush(PushLikeDTO likeDTO) {
        Long pushId = likeDTO.getPushId();
        Long userId = likeDTO.getUserId();
        
        // 检查是否已经点赞
        QueryWrapper<PushLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("push_id", pushId).eq("user_id", userId);
        PushLike existingLike = pushLikeMapper.selectOne(queryWrapper);
        
        if (existingLike != null) {
            throw new RuntimeException("您已经点赞过此推文");
        }
        
        // 创建点赞记录
        PushLike pushLike = new PushLike();
        pushLike.setPushId(pushId);
        pushLike.setUserId(userId);
        pushLikeMapper.insert(pushLike);
        
        // 更新推文点赞数（原子自增，仅未删除）
        UpdateWrapper<Push> likeInc = new UpdateWrapper<>();
        likeInc.eq("id", pushId).isNull("deleted_at").setSql("like_count = like_count + 1");
        pushMapper.update(null, likeInc);
        
        log.info("用户 {} 点赞推文 {} 成功", userId, pushId);
    }

    @Override
    @Transactional
    public void unlikePush(PushLikeDTO likeDTO) {
        Long pushId = likeDTO.getPushId();
        Long userId = likeDTO.getUserId();
        
        // 查找点赞记录
        QueryWrapper<PushLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("push_id", pushId).eq("user_id", userId);
        PushLike existingLike = pushLikeMapper.selectOne(queryWrapper);
        
        if (existingLike == null) {
            throw new RuntimeException("您还没有点赞过此推文");
        }
        
        // 删除点赞记录
        pushLikeMapper.deleteById(existingLike.getId());
        
        // 更新推文点赞数（原子自减，防止负数）
        UpdateWrapper<Push> likeDec = new UpdateWrapper<>();
        likeDec.eq("id", pushId).isNull("deleted_at").setSql("like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END");
        pushMapper.update(null, likeDec);
        
        log.info("用户 {} 取消点赞推文 {} 成功", userId, pushId);
    }

    @Override
    @Transactional
    public void addComment(PushCommentDTO commentDTO) {
        Long pushId = commentDTO.getPushId();
        Long userId = commentDTO.getUserId();
        String content = commentDTO.getContent();
        
        // 创建评论记录
        PushComment comment = new PushComment();
        comment.setPushId(pushId);
        comment.setUserId(userId);
        comment.setContent(content);
        // 填充用户名以符合表结构要求
        User user = userService.getById(userId);
        String displayName = (user != null && StringUtils.hasText(user.getNickname())) ? user.getNickname() : (user != null ? user.getUsername() : "");
        comment.setUserName(displayName);
        pushCommentMapper.insert(comment);
        
        // 更新推文评论数（原子自增）
        UpdateWrapper<Push> commentInc = new UpdateWrapper<>();
        commentInc.eq("id", pushId).isNull("deleted_at").setSql("comment_count = comment_count + 1");
        pushMapper.update(null, commentInc);
        
        log.info("用户 {} 评论推文 {} 成功", userId, pushId);
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        // 查找评论记录
        PushComment comment = pushCommentMapper.selectById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 检查权限（只能删除自己的评论）
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除此评论");
        }
        
        // 删除评论
        pushCommentMapper.deleteById(commentId);
        
        // 更新推文评论数（原子自减，防止负数）
        UpdateWrapper<Push> commentDec = new UpdateWrapper<>();
        commentDec.eq("id", comment.getPushId()).isNull("deleted_at").setSql("comment_count = CASE WHEN comment_count > 0 THEN comment_count - 1 ELSE 0 END");
        pushMapper.update(null, commentDec);
        
        log.info("用户 {} 删除评论 {} 成功", userId, commentId);
    }

    @Override
    public PageResult<PushCommentVO> getComments(Long pushId, Integer current, Integer size, Long userId) {
        // 创建分页对象
        Page<PushComment> page = new Page<>(current, size);
        
        // 构建查询条件
        QueryWrapper<PushComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("push_id", pushId);
        queryWrapper.isNull("deleted_at"); // 只查询未删除的评论
        queryWrapper.orderByDesc("created_at"); // 按创建时间倒序
        
        // 执行分页查询
        IPage<PushComment> commentPage = pushCommentMapper.selectPage(page, queryWrapper);
        
        // 转换为VO对象
        List<PushCommentVO> commentVOList = commentPage.getRecords().stream()
            .map(this::convertToCommentVO)
            .collect(Collectors.toList());
        
        // 构建分页结果
        return PageResult.of(commentVOList, commentPage.getTotal(), (long) current, (long) size);
    }

    @Override
    public List<PushCommentVO> getAllComments(Long pushId, Long userId) {
        // 查询所有评论
        QueryWrapper<PushComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("push_id", pushId);
        queryWrapper.isNull("deleted_at"); // 只查询未删除的评论
        queryWrapper.orderByDesc("created_at");
        
        List<PushComment> comments = pushCommentMapper.selectList(queryWrapper);
        
        // 转换为VO对象
        return comments.stream()
            .map(this::convertToCommentVO)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void likeComment(Long commentId, Long userId) {
        // TODO: 实现评论点赞功能
        log.info("用户 {} 点赞评论 {} 成功", userId, commentId);
    }

    @Override
    @Transactional
    public void unlikeComment(Long commentId, Long userId) {
        // TODO: 实现取消评论点赞功能
        log.info("用户 {} 取消点赞评论 {} 成功", userId, commentId);
    }

    @Override
    public PageResult<UserPushVO> getLikedPushes(Long userId, Integer current, Integer size) {
        // 创建分页对象
        Page<Push> page = new Page<>(current, size);
        
        // 查询用户点赞的推文ID列表
        QueryWrapper<PushLike> likeQuery = new QueryWrapper<>();
        likeQuery.eq("user_id", userId);
        List<PushLike> userLikes = pushLikeMapper.selectList(likeQuery);
        
        if (userLikes.isEmpty()) {
            return PageResult.of(new ArrayList<>(), 0L, (long) current, (long) size);
        }
        
        List<Long> pushIds = userLikes.stream()
            .map(PushLike::getPushId)
            .collect(Collectors.toList());
        
        // 查询推文详情（仅未删除）
        QueryWrapper<Push> pushQuery = new QueryWrapper<>();
        pushQuery.in("id", pushIds).isNull("deleted_at");
        // pushQuery.eq("status", 1);
        pushQuery.orderByDesc("created_at");
        
        IPage<Push> pushPage = pushMapper.selectPage(page, pushQuery);
        
        // 转换为VO对象
        List<UserPushVO> userPushVOList = pushPage.getRecords().stream()
            .map(this::convertToUserPushVO)
            .collect(Collectors.toList());
        
        // 设置已点赞状态
        userPushVOList.forEach(vo -> vo.setIsLiked(true));
        
        // 构建分页结果
        return PageResult.of(userPushVOList, pushPage.getTotal(), (long) current, (long) size);
    }

    /**
     * 将Push实体转换为UserPushVO
     */
    private UserPushVO convertToUserPushVO(Push push) {
        UserPushVO userPushVO = new UserPushVO();
        BeanUtils.copyProperties(push, userPushVO);
        
        // 这里需要根据publisherId查询发布者姓名
        // 暂时设置为null，后续可以通过关联查询获取
        userPushVO.setPublisherName("管理员"); // 临时设置
        
        return userPushVO;
    }

    /**
     * 将PushComment实体转换为PushCommentVO
     */
    private PushCommentVO convertToCommentVO(PushComment comment) {
        PushCommentVO commentVO = new PushCommentVO();
        BeanUtils.copyProperties(comment, commentVO);
        // 设置评论者姓名、头像
        commentVO.setUsername(comment.getUserName());
        try {
            if (comment.getUserId() != null) {
                User u = userService.getById(comment.getUserId());
                if (u != null) {
                    if (!org.springframework.util.StringUtils.hasText(commentVO.getUsername())) {
                        commentVO.setUsername(org.springframework.util.StringUtils.hasText(u.getNickname()) ? u.getNickname() : u.getUsername());
                    }
                    commentVO.setAvatar(u.getAvatar());
                }
            }
        } catch (Exception ignore) {}
        
        return commentVO;
    }
}
